import React, { useState, useEffect } from 'react';
import { Card, SegmentedControl, WhiteSpace, Flex, WingBlank, Icon } from 'antd-mobile';
import { Divider, Tooltip } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import * as utils from './utils/index';
import FileBtn from '@/components/FileBtn';
import styles from './index.less';
import YearTarget from './components/YearTarget';
import MonthTarget from './components/MonthTarget';
import Difference from './components/Difference';

const ApproveMobile = props => {
  utils.createDom();
  const { items } = props;
  const { files, organizationDto } = items;
  const [tabKey, setTabKey] = useState(0);
  const [tabs, setTabs] = useState([]);
  const [tabs1key, setTabs1key] = useState(0);
  const [overallYearIndexList, setOverallYearIndexList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState('');
  /* 设置容器的高度 */
  const setDomeHeight = num => {
    if (window.cifioa) {
      window.cifioa.sendMessage({
        type: 'height',
        height: num,
      });
    }
  };
  useEffect(() => {
    setDomeHeight(150);
    const { dispatch, location } = props;
    const params = {
      billId: location.query.id,
      projectId: '',
    };
    dispatch({
      type: 'SigningApproveMobile/info',
      payload: { params },
      callback: response => {
        if (response.code === 1) {
          setLoading(!loading);
          const appRoveMobile = document.getElementById('appRoveMobile');
          setDomeHeight(appRoveMobile.offsetHeight - 10);
        } else {
          setLoading(!loading);
          setMessage(response.message);
        }
      },
    });
  }, []);

  // 获取切换的年
  useEffect(() => {
    if (Object.keys(items).length > 0 && items.overallYearIndexList.length > 0) {
      const arr = [];
      _.each(items.overallYearIndexList, v => {
        arr.push({
          title: `${v.year}年`,
          key: v.year,
        });
      });
      setTabs(arr);
      setTabKey(arr[0].key);
    }
  }, [items]);

  // 筛选点击当前的数据
  useEffect(() => {
    if (!_.isEmpty(tabKey)) {
      setOverallYearIndexList(_.filter(items.overallYearIndexList, v => v.year === tabKey)[0]);
    }
  }, [tabKey]);

  useEffect(() => {
    const appRoveMobile = document.getElementById('appRoveMobile');
    setDomeHeight(appRoveMobile.offsetHeight - 10);
  }, [tabs1key]);

  return (
    <div className={styles['app-rove-mobile']}>
      {/* 加载 */}
      <div style={{ height: loading ? '150px' : '0px', background: '#fff' }}>
        <WingBlank>
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%,-50%)',
            }}
          >
            {loading ? <Icon type="loading" size="lg" /> : null}
          </div>
        </WingBlank>
      </div>
      <div style={{ height: message !== '' ? '150px' : '0px', background: '#fff' }}>
        <WingBlank>
          <div
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%,-50%)',
            }}
          >
            {message}
          </div>
        </WingBlank>
      </div>
      <div id="appRoveMobile">
        {loading ? null : (
          <>
            <Card full style={{ marginTop: '-10px' }}>
              {/* 基本信息 */}
              <WhiteSpace />
              <WingBlank>
                <div className="title">基本信息</div>
                <WhiteSpace />
                <Flex justify="between">
                  <Tooltip
                    placement="topLeft"
                    title={`${items.projectName}(${items.projectCode})` || '无'}
                  >
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                      <span className="ellipsis font2">
                        <span className="font1">项目：</span>
                        {`${items.projectName}（${items.projectCode}）` || '无'}
                      </span>
                    </div>
                  </Tooltip>
                </Flex>
                <Flex justify="between">
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <span className="font1">区域：</span>
                    <span className="font2">{items.regionName || '无'}</span>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <span className="font1">权益比例：</span>
                    <span className="font2">{`${items.equityRatio * 1} %`}</span>
                  </div>
                </Flex>
              </WingBlank>
              <WhiteSpace />
              <Divider />
              {/* 本次编排版本 */}
              <WhiteSpace />
              <WingBlank>
                <div className="title">本次编排版本</div>
                <WhiteSpace />
                {organizationDto.stageNames.map((v, i) => (
                  <div
                    style={{ display: 'flex', alignItems: 'center' }}
                    key={`${v.substring(3) + i}`}
                  >
                    <WhiteSpace />
                    <span className="font1">{v.substring(0, 2)}：</span>
                    <span className="ellipsis font2">{v.substring(3)}</span>
                  </div>
                ))}
              </WingBlank>
              <WhiteSpace />
              <Divider />
              {/* 审批要点说明 */}
              <WhiteSpace />
              <WingBlank>
                <div className="title">审批要点说明</div>
                <div className="font2">{items.description}</div>
              </WingBlank>
              <WhiteSpace />
              {files && !_.isEmpty(files) ? <Divider /> : null} {/* 如果附件不为空加分割线 */}
              {/* 附件 附件为空则不显示 */}
              {files && !_.isEmpty(files) ? (
                <>
                  <WhiteSpace />
                  <WingBlank>
                    <div className="title">附件</div>
                    {items.files.map(v => (
                      <FileBtn
                        fileId={v.fileId}
                        fileName={v.fileName}
                        clickType="btnClick"
                        titleNmae
                        key={v.fileId}
                        download={true}
                      />
                    ))}
                  </WingBlank>
                  <WhiteSpace />
                </>
              ) : null}
            </Card>
            <WhiteSpace />
            {/* 表格部分 */}
            <Card full>
              <WhiteSpace />
              <WingBlank>
                <div className="title">全盘年度指标</div>
              </WingBlank>
              <div className="xh-approve-tabs">
                {tabs.map(v => (
                  <div className="xh-approve-tabs-default-tab" key={v.key}>
                    <div
                      onClick={() => setTabKey(v.key)}
                      style={{
                        color: tabKey === v.key ? '#2761FF' : 'rgba(153, 153, 153, 1)',
                      }}
                      className="xh-approve-tabs-default-tab-text"
                    >
                      <span>{v.title}</span>
                      <div
                        className="xh-approve-tabs-default-tab-active"
                        style={{ background: tabKey === v.key ? '#2761FF' : '#e6e6e6' }}
                      ></div>
                    </div>
                  </div>
                ))}
              </div>
              <div>
                <WhiteSpace />
                <Card.Body>
                  <Flex justify="center">
                    <SegmentedControl
                      style={{ height: '30px', width: '224px' }}
                      values={['年度指标概览', '年度指标差异']}
                      selectedIndex={tabs1key}
                      onChange={e => setTabs1key(e.nativeEvent.selectedSegmentIndex)}
                    />
                  </Flex>
                </Card.Body>
                <YearTarget yearIndex={overallYearIndexList.yearIndex} tabs1key={tabs1key} />
                <WhiteSpace />
                <MonthTarget
                  yearEarlyBottomList={overallYearIndexList.yearEarlyBottomList}
                  year={overallYearIndexList.year}
                />
                <WhiteSpace />
              </div>
            </Card>
            <WhiteSpace />
            <Card full style={{ marginBottom: '-10px' }}>
              <WhiteSpace />
              <WingBlank>
                <div className="title">月均销售同比偏差</div>
              </WingBlank>
              <Difference {...items} />
            </Card>
          </>
        )}
      </div>
    </div>
  );
};

export default connect(state => ({
  items: state.SigningApproveMobile.item,
}))(ApproveMobile);
